package org.oa.ai.chatController;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import dev.langchain4j.data.message.*;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.service.TokenStream;
import jakarta.servlet.http.HttpServletResponse;
import okhttp3.*;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import org.apache.poi.xwpf.usermodel.*;
import org.oa.ai.chatModel.ApifoxModel;
import org.oa.ai.chatModel.InputStreamMultipartFile;
import org.oa.ai.chatModel.OcrRequest;
import org.oa.ai.chatModel.SwModel;
import org.oa.ai.config.GwAssistant;
import org.oa.ai.feign.AIFeignClient;
import org.oa.ai.feign.AIFeignService;
import org.oa.ai.model.ModelService;
import org.oa.ai.word.WordToHtmlUtil;
import org.oa.ai.word.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.*;
import java.time.Duration;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/gw/old")
@CrossOrigin
public class GwController {

    @Autowired
    private ModelService modelService;

    @Autowired
    private AIFeignService aiFeignService;

    @Value("${fc.username}")
    private String username;

    @Value("${fc.password}")
    private String password;

    @Value("${fc.url}")
    private String url;

    public Object userToken;

    @Autowired
    private GwAssistant gwAssistant;

    @CrossOrigin
    @PostMapping("/auth/login")
    public JSONObject authLogin(@RequestBody Map<String, Object> map) {
        JSONObject result = new JSONObject();
        // 获取用户名和密码
        Object usernameObj = map.get("username");
        Object passwordObj = map.get("password");

        if (usernameObj == null || passwordObj == null) {
            return null; // 参数缺失直接返回
        }

        String username = usernameObj.toString();
        String password = passwordObj.toString();

        JSONObject loginObj = new JSONObject();
        loginObj.set("username", username);
        loginObj.set("password", password);

        // 第一次登录尝试
        JSONObject loginResult = login(loginObj);

        if (loginResult == null) {
            return null; // 登录接口异常或无返回
        }

        int code = loginResult.getInt("code");

        if (code == 500) {
            JSONObject userCreateObj = new JSONObject();
            userCreateObj.set("nickName", username);
            userCreateObj.set("username", username);
            userCreateObj.set("pwd", password); // 使用原始密码而非用户名作为密码

            // 查询用户是否存在
            JSONObject userInfo = getUserInfo(username);
            JSONObject data = userInfo != null ? userInfo.getJSONObject("data") : null;

            if (data == null) {
                // 用户不存在则新增
                JSONObject addResult = addUser(userCreateObj);
                if (addResult != null && addResult.getInt("code") == 200) {
                    // 新增成功后再次登录
                    JSONObject retryLogin = login(loginObj);
                    if (retryLogin != null && retryLogin.getJSONObject("data") != null) {
                        result.set("code",  addResult.getInt("code"));
                        result.set("msg", addResult.getStr("message"));
                        result.set("token",  retryLogin.getJSONObject("data").getStr("token"));
                        return result;
                    }
                } else {
                    result.set("code", addResult.getInt("code"));
                    result.set("msg", "请联系管理员！" + addResult.getStr("message"));
                    // 新增失败
                    return result;
                }
            } else {
                // 用户存在但登录失败，可能是密码错误
                result.set("code", 500);
                result.set("msg", "请联系管理员！账号或密码错误！");
                return null;
            }
        } else if (code == 200) {
            // 登录成功直接返回 token
            result.set("code",  loginResult.getInt("code"));
            result.set("msg", loginResult.getStr("message"));
            result.set("token",  loginResult.getJSONObject("data").getStr("token"));
            return result;
        }

        return null;
    }

    /**
     * 获取方寸用户token
     */
    public JSONObject login(JSONObject loginObj) {
        // 登录用户获取token
        try {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            okhttp3.MediaType mediaType = MediaType.parse("application/json");
            okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, JSONUtil.toJsonStr(loginObj));
            Request request = new Request.Builder()
                    .url(url + "/user/login")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = null;
            response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                // 使用 Gson 解析 JSON
                return new JSONObject(responseBody.string());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


    /**
     * 获取方寸用户token
     */
    public void setToken() {
        // 登录用户获取token
        try {
            JSONObject loginObj = new JSONObject();
            loginObj.set("username", username);
            loginObj.set("password", password);
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            okhttp3.MediaType mediaType = MediaType.parse("application/json");
            okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, JSONUtil.toJsonStr(loginObj));
            Request request = new Request.Builder()
                    .url(url + "/user/login")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = null;
            response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                // 使用 Gson 解析 JSON
                JSONObject result = new JSONObject(responseBody.string());
                JSONObject data = result.getJSONObject("data");
                userToken = data.get("token");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用方寸的接口调用大模型，以文写文
     *  action: 3：续写; 4：扩写(段落); 5：改写； 6：提炼； 9：扩写(提纲)
     *  请示1 公告2 函3 公报5 决定6 决议7 令类8 报告9 批复10 议案12 通告13 通报14 通知15
     */
    @CrossOrigin
    @PostMapping(value = "/docDraft", produces = "text/event-stream;charset=UTF-8")  // 设置返回给前端文本的编码
    public SseEmitter docDraft(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }
        String jsonStr = JSONUtil.toJsonStr(map);
        // 创建请求
        Request request = new Request.Builder()
//                .url(url + "/intelligent/document/writing") // 使用配置URL
                .url(url + "/intelligent/document/writing/v2") // 使用配置URL
                .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                .build();
        // 创建 client
//        OkHttpClient client = new OkHttpClient().newBuilder().build();

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                .build();

        // 流式处理响应
        SseEmitter emitter = new SseEmitter(100_000L); // 设置超时时间
        new Thread(() -> {
            Response response = null;
            try {
                response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    emitter.onError(Throwable::printStackTrace);
                    return;
                }
                ResponseBody body = response.body();
                if (body == null) {
                    emitter.complete();
                    return;
                }
                // 处理SSE流式响应
                BufferedSource source = body.source();
                while (!source.exhausted()) {
                    String line = source.readUtf8Line();
                    if (line == null) break;
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if (data.startsWith("{") && data.endsWith("}")) {
                            JSONObject jsObj = JSONUtil.parseObj(data).getJSONObject("data");
                            if(jsObj != null) {
                                String content = jsObj.getStr("content");
                                System.out.println(content);
                                emitter.send(SseEmitter.event().name("message").data(content));
                            }
                        }
                    }
                }
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            } finally {
                if (response != null) response.close();
            }
            emitter.complete();
        }).start();
        return emitter;
    }

    /**
     * 使用方寸的接口调用大模型，优化改稿
     */
    @CrossOrigin
    @PostMapping(value = "/optimizeRewrite", produces = "text/event-stream;charset=UTF-8")  // 设置返回给前端文本的编码
    public SseEmitter optimizeRewrite(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }
        String jsonStr = JSONUtil.toJsonStr(map);
        // 创建请求
        Request request = new Request.Builder()
                .url(url + "/intelligent/document/writing/tool") // 使用配置URL
                .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                .build();
        // 创建 client
//        OkHttpClient client = new OkHttpClient().newBuilder().build();

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                .build();

        // 流式处理响应
        SseEmitter emitter = new SseEmitter(100_000L); // 设置超时时间
        new Thread(() -> {
            Response response = null;
            try {
                response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    emitter.onError(Throwable::printStackTrace);
                    return;
                }
                ResponseBody body = response.body();
                if (body == null) {
                    emitter.complete();
                    return;
                }
                // 处理SSE流式响应
                BufferedSource source = body.source();
                while (!source.exhausted()) {
                    String line = source.readUtf8Line();
                    if (line == null) break;
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if (data.startsWith("{") && data.endsWith("}")) {
                            JSONObject jsObj = JSONUtil.parseObj(data).getJSONObject("data");
                            if(jsObj != null) {
                                String content = jsObj.getStr("content");
                                System.out.println(content);
                                emitter.send(SseEmitter.event().name("message").data(content));
                            }
                        }
                    }
                }
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            } finally {
                if (response != null) response.close();
            }
            emitter.complete();
        }).start();
        return emitter;
    }

    /**
     * 使用方寸的接口调用大模型，纠正错别字等
     */
    @CrossOrigin
    @PostMapping(value = "/correction")  // 设置返回给前端文本的编码
    public JSONObject correction(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String string = map.get("text").toString();
            map.put("text", formatMarkdown(string));
            String jsonStr = JSONUtil.toJsonStr(map);

            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/document/correction") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
//            OkHttpClient client = new OkHttpClient().newBuilder().build();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                    .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                    .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    public String formatMarkdown(String input) {
        // 找到 <think> 和 </think> 的位置
        int startIndex = input.indexOf("<think>");
        int endIndex = input.indexOf("</think>") + "</think>".length();
        // 删除 <think> 标签及其内容
        String result;
        if (startIndex != -1 && endIndex != -1) {
            result = input.substring(0, startIndex) + input.substring(endIndex);
        } else {
            result = input; // 如果没有找到标签，返回原字符串
        }
        return result;
    }

    /**
     * 使用方寸的接口调用大模型，获取国标文件
     */
    @CrossOrigin
    @GetMapping(value = "/getStandardFile")  // 设置返回给前端文本的编码
    public JSONObject getStandardFile(){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/userDictionary/officialDocumentTemplate/web/getAppliedTempList") // 使用配置URL
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，通过文本识别要素
     */
    @CrossOrigin
    @PostMapping(value = "/identifyingFeature")  // 设置返回给前端文本的编码
    public String identifyingFeature(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String string = map.get("content").toString();
            map.put("content", formatMarkdown(string));
            String jsonStr = JSONUtil.toJsonStr(map);

            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/ai-api/text-element-extract/text_extract") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                return responseBody.string();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }


    /**
     * 使用方寸的接口调用大模型，智能排版，直接返回文件流（启用，保留）
     */
//    @CrossOrigin
//    @GetMapping(value = "/smartComposing")  // 设置返回给前端文本的编码
//    public void smartComposing(@RequestParam Map<String, Object> map,  HttpServletResponse returnResponse){
//
//        // 先获取token
//        if (userToken == null) {
//            setToken();
//        }
//        try {
//
//            ApifoxModel bean = JSONUtil.toBean(JSONUtil.parseObj(map), ApifoxModel.class);
//
////            ApifoxModel apifoxModel = new ApifoxModel();
////            apifoxModel.setFileKey("g_1");
////            apifoxModel.setAttachmentsExplainFlag("0");
////            apifoxModel.setBiaoti("关于召开集团公司2025年度工作会议的通知");
////            apifoxModel.setZhusongjiguan("各成员单位、集团公司各部门");
////            apifoxModel.setZhengwen("根据集团公司年度工作安排，为全面总结2024年工作成果、部署2025年重点任务，经研究决定召开集团公司2025年度工作会议。");
//            String jsonStr = JSONUtil.toJsonStr(bean);
//
//            OkHttpClient client = new OkHttpClient().newBuilder()
//                    .build();
//            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
//            okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, jsonStr);
//            Request request = new Request.Builder()
//                    .url(url + "/layout/layoutByTemplate")
//                    .method("POST", body)
//                    .addHeader("Content-Type", "application/json; charset=utf-8")
//                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
//                    .build();
//            Response response = client.newCall(request).execute();
//
//            ResponseBody responseBody = response.body();
//            if (responseBody != null) {
//
//                // 设置响应头
//                returnResponse.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); // Word 文件类型
//                returnResponse.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.docx");
//
//                // 获取输入流和输出流
//                InputStream inputStream = responseBody.byteStream();
//                OutputStream outputStream = returnResponse.getOutputStream();
//
//                byte[] buffer = new byte[10240];
//                int bytesRead;
//
//                while ((bytesRead = inputStream.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, bytesRead);
//                }
//
//                // 关闭流
//                inputStream.close();
//                outputStream.flush();
//                outputStream.close();
//
//
//                // 获取输入流
////                InputStream inputStream = responseBody.byteStream();
//////
//////                // 举例：将流写入本地文件
////                File fileToSave = new File("E:/file.docx"); // 根据实际类型命名
////                FileOutputStream fileOutputStream = new FileOutputStream(fileToSave);
//////
////                byte[] buffer = new byte[10240];
////                int bytesRead;
////                while ((bytesRead = inputStream.read(buffer)) != -1) {
////                    fileOutputStream.write(buffer, 0, bytesRead);
////                }
////
////
////                System.out.println("文件保存成功: " + fileToSave.getAbsolutePath());
//            }
//
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }

    /**
     * 使用方寸的接口调用大模型，智能排版，直接返回文件id
     */
    @CrossOrigin
    @PostMapping(value = "/smartComposing/{gwid}/{ywlx}/{userId}")  // 设置返回给前端文本的编码
    public JSONObject smartComposing(@RequestBody ApifoxModel bean, @PathVariable("gwid") String gwid, @PathVariable("ywlx") String ywlx, @PathVariable("userId") String userId){

        // 先获取token
        if (userToken == null) {
            setToken();
        }
        try {
//            ApifoxModel bean = JSONUtil.toBean(JSONUtil.parseObj(map), ApifoxModel.class);
            String jsonStr = JSONUtil.toJsonStr(bean);
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, jsonStr);
            Request request = new Request.Builder()
                    .url(url + "/layout/layoutByTemplate")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            Response response = client.newCall(request).execute();

            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                // 获取输入流
                InputStream inputStream = responseBody.byteStream();
                // 将 InputStream 转换为 MultipartFile
                MultipartFile multipartFile = new InputStreamMultipartFile(
                        "file",
                        "file.docx",
                        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                        inputStream
                );

                // 调用OA接口上传文件
                JSONObject jsonObject = aiFeignService.fileUpload(multipartFile, gwid, ywlx, userId);
                return jsonObject;

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，篇章校对
     */
    @CrossOrigin
    @PostMapping(value = "/proofread")  // 设置返回给前端文本的编码
    public JSONObject proofread(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String jsonStr = JSONUtil.toJsonStr(map);

            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/proofread/onlineProofread/asyncProofread") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                return new JSONObject(responseBody.string());
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，查询篇幅校对结果
     */
    @CrossOrigin
    @PostMapping(value = "/queryProofreadResult")  // 设置返回给前端文本的编码
    public JSONObject queryProofreadResult(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String jsonStr = JSONUtil.toJsonStr(map);

            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/proofread/onlineProofread/asyncProofreadResult") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                return new JSONObject(responseBody.string());
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 调用方寸模型，上传本地附件
     */
    @CrossOrigin
    @PostMapping(value = "/uploadFile")  // 设置返回给前端文本的编码
    public JSONObject uploadFile(@RequestParam("file") MultipartFile file){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            okhttp3.RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file",file.getOriginalFilename(),
                            okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), file.getBytes()))
                    .build();
            Request request = new Request.Builder()
                    .url(url + "/intelligent/document/uploadFile")
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 流式处理响应
        return null;
    }

    /**
     * 调用方寸模型，上传本地附件，以文写文
     */
    @CrossOrigin
    @PostMapping(value = "/local/uploadFile")  // 设置返回给前端文本的编码
    public JSONObject localUploadFile(@RequestParam("file") MultipartFile file){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            okhttp3.RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file",file.getOriginalFilename(),
                            okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), file.getBytes()))
                    .build();
            Request request = new Request.Builder()
                    .url(url + "/intelligent/document/user/uploadFile")
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 流式处理响应
        return null;
    }

    /**
     * 调用方寸模型，OCR识别：通过文件上传识别文件内容
     */
    @CrossOrigin
    @PostMapping(value = "/ocr/uploadFile")  // 设置返回给前端文本的编码
    public JSONObject ocrUploadFile(@RequestParam("file") MultipartFile file){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            okhttp3.RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file",file.getOriginalFilename(),
                            okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), file.getBytes()))
                    .build();
            Request request = new Request.Builder()
                    .url(url + "/ocr/identificationDoc")
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 流式处理响应
        return null;
    }

    /**
     * 调用方寸模型，OCR识别：通过文件图片id进行获取图片
     */
    @CrossOrigin
    @GetMapping(value = "/getOcrImg/{id}")  // 设置返回给前端文本的编码
    public JSONObject getOcrImg(@PathVariable("id") String id, HttpServletResponse responseServlet){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/ocr/preview/"+id) // 使用配置URL
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null && "image/jpeg".equals(responseBody.contentType().toString())) {
                responseServlet.setContentType("image/jpeg");
                try (InputStream inputStream = responseBody.byteStream();
                     OutputStream outputStream = responseServlet.getOutputStream()) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
            } else {
                responseServlet.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }


    /**
     * 带着存储使用流式方式返回数据并区分用户隔离
     */
    @CrossOrigin
    @PostMapping("/sendMessage")  // 设置返回给前端文本的编码
    public SwModel assistantUniqueStream(@RequestBody OcrRequest ocrRequest) {
        SwModel stream = gwAssistant.stream(ocrRequest.getUserId(), ocrRequest.getMessage());
        return stream;
    }

    /**
     * 通过正文id获取正文内容，通过正文内容进行提炼数据
     * @return
     */
    @CrossOrigin
    @PostMapping(value = "/extractData/{zw}", produces = "text/event-stream;charset=UTF-8")  // 设置返回给前端文本的编码
    public SseEmitter extractData(@PathVariable("zw") String zw){
        Map<String, Object> map = new HashMap<>();
        // 先获取文件中的所有内容
        String zwContent = aiFeignService.getFileContent(zw);
        map.put("action", 6);
        map.put("officialDocType", 15);
        map.put("prompt", zwContent);
        // 先获取token
        if (userToken == null) {
            setToken();
        }
        String jsonStr = JSONUtil.toJsonStr(map);
        // 创建请求
        Request request = new Request.Builder()
//                .url(url + "/intelligent/document/writing") // 使用配置URL
                .url(url + "/intelligent/document/writing/v2") // 使用配置URL
                .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                .build();
        // 创建 client
//        OkHttpClient client = new OkHttpClient().newBuilder().build();

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                .build();

        // 流式处理响应
        SseEmitter emitter = new SseEmitter(100_000L); // 设置超时时间
        new Thread(() -> {
            Response response = null;
            try {
                response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    emitter.onError(Throwable::printStackTrace);
                    return;
                }
                ResponseBody body = response.body();
                if (body == null) {
                    emitter.complete();
                    return;
                }
                // 处理SSE流式响应
                BufferedSource source = body.source();
                while (!source.exhausted()) {
                    String line = source.readUtf8Line();
                    if (line == null) break;
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if (data.startsWith("{") && data.endsWith("}")) {
                            JSONObject jsObj = JSONUtil.parseObj(data).getJSONObject("data");
                            if(jsObj != null) {
                                String content = jsObj.getStr("content");
                                System.out.println(content);
                                emitter.send(SseEmitter.event().name("message").data(content));
                            }
                        }
                    }
                }
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            } finally {
                if (response != null) response.close();
            }
            emitter.complete();
        }).start();
        return emitter;
    }

    /**
     * 使用方寸的接口调用大模型，查询政策工文库数量
     */
    @CrossOrigin
    @PostMapping(value = "/getRetrievalDataSum")  // 设置返回给前端文本的编码
    public JSONObject getRetrievalDataSum(){
        // 先获取token
        if (userToken == null) {
            setToken();
        }
        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/getRetrievalDataSum") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), ""))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，查询用户本地工文库
     */
    @CrossOrigin
    @PostMapping(value = "/userRepository")  // 设置返回给前端文本的编码
    public JSONObject getLoaclLib(){
        // 先获取token
        if (userToken == null) {
            setToken();
        }
        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/user/resource/repository/allList/byOutLineTitle") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), ""))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，地区分类查询
     */
    @CrossOrigin
    @PostMapping(value = "/getCityRegion")  // 设置返回给前端文本的编码
    public JSONObject getCityRegion(){
        // 先获取token
        if (userToken == null) {
            setToken();
        }
        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/searchCondition/getCityRegion") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), ""))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，获取检索文章类型
     */
    @CrossOrigin
    @GetMapping(value = "/getConditionType/{code}")  // 设置返回给前端文本的编码
    public JSONObject getCondition(@PathVariable("code") Integer code){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/searchCondition/type?code=" + code) // 使用配置URL
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，查询最新入库文件
     */
    @CrossOrigin
    @GetMapping(value = "/getRecent")  // 设置返回给前端文本的编码
    public JSONObject getRecent(){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/user/resource/repository/doc/recent?searchFlag=1&size=20") // 使用配置URL
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，查询我的收藏
     */
    @CrossOrigin
    @GetMapping(value = "/getMyFavorite")  // 设置返回给前端文本的编码
    public JSONObject getMyFavorite(){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/retrieval/collection/list?page=1&size=1000000") // 使用配置URL
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，通过条件智能检索
     */
    @CrossOrigin
    @PostMapping(value = "/retrieval")  // 设置返回给前端文本的编码
    public JSONObject retrieval(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String jsonStr = JSONUtil.toJsonStr(map);
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/retrieval/v2") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
//            OkHttpClient client = new OkHttpClient().newBuilder().build();

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                    .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                    .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，获取公文详情
     */
    @CrossOrigin
    @GetMapping(value = "/getDetail/{sourceId}")  // 设置返回给前端文本的编码
    public JSONObject getDetail(@PathVariable("sourceId") String sourceId){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/retrieval/detail?sourceId=" + sourceId) // 使用配置URL
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，获取公文目录结构
     */
    @CrossOrigin
    @GetMapping(value = "/getOutline/{sourceId}")  // 设置返回给前端文本的编码
    public JSONObject getOutline(@PathVariable("sourceId") String sourceId){
        // 先获取token
        if (userToken == null) {
            setToken();
        }
        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/outline?sourceId=" + sourceId) // 使用配置URL
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，获取关键句摘录
     */
    @CrossOrigin
    @GetMapping(value = "/getPunchline/{sourceId}")  // 设置返回给前端文本的编码
    public JSONObject getPunchline(@PathVariable("sourceId") String sourceId){
        // 先获取token
        if (userToken == null) {
            setToken();
        }
        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/punchline?sourceId=" + sourceId) // 使用配置URL
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，内容摘要
     */
    @CrossOrigin
    @PostMapping(value = "/getRightAssistRead")  // 设置返回给前端文本的编码
    public JSONObject getRightAssistRead(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String jsonStr = JSONUtil.toJsonStr(map);
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/getRightAssistRead") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
//            OkHttpClient client = new OkHttpClient().newBuilder().build();

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                    .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                    .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，加入收藏
     */
    @CrossOrigin
    @PostMapping(value = "/addCollection")  // 设置返回给前端文本的编码
    public JSONObject addCollection(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String jsonStr = JSONUtil.toJsonStr(map);
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/retrieval/collection/add") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
//            OkHttpClient client = new OkHttpClient().newBuilder().build();

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                    .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                    .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 使用方寸的接口调用大模型，加入收藏
     */
    @CrossOrigin
    @PostMapping(value = "/delCollection")  // 设置返回给前端文本的编码
    public JSONObject delCollection(@RequestBody Map<String, Object> map){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String jsonStr = JSONUtil.toJsonStr(map);
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/intelligent/retrieval/collection/delete") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
//            OkHttpClient client = new OkHttpClient().newBuilder().build();

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                    .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                    .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }


    /**
     * 将用户数据同步到方寸模型中
     */
    @CrossOrigin
    @GetMapping(value = "/addAllUser/{id}")  // 设置返回给前端文本的编码
    public JSONObject addAllUser(@PathVariable("id") String userId){
        // 1.获取要新增的用户
        JSONArray jsonArray = aiFeignService.getAllUsers(userId);

        // 2.判断当前是否登录
        if (userToken == null) {
            setToken();
        }

        JSONArray addSuccess = new JSONArray();  // 新增成功用户
        JSONArray addError = new JSONArray();   // 新增失败用户

        // 遍历新增
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            JSONObject object = new JSONObject();
            object.set("nickName", jsonObject.getStr("name"));
            object.set("username", "sr" + jsonObject.getStr("login_name"));
            object.set("pwd", "sr" + jsonObject.getStr("login_name"));

            // 3.查询用户是否存在
            JSONObject userInfo = getUserInfo(object.getStr("username"));
            JSONObject data = userInfo.getJSONObject("data");

            // 4.如果用户存在则修改用户信息
            if (data == null) {
                JSONObject result = addUser(object);
                System.out.println(result);
                if (result.getInt("code") == 200) {
                    addSuccess.add(object);
                }else {
                    addError.add(object);
                }
            }
        }

        // 构建返回数据
        JSONObject result = new JSONObject();
        result.set("addSuccess", addSuccess);
        result.set("addError", addError);
        result.set("successNum", addSuccess.size());
        result.set("errNum", addError.size());
        result.set("totalNum", jsonArray.size());

        return result;
    }

    /**
     * 查询用户
     */
    public JSONObject getUserInfo(String username){
        try {
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/company/people/findByUsername?username=" + username) // 使用配置URL
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();
            // 创建 client
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject jsonObject = new JSONObject(responseBody.string());
                return jsonObject;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 新增用户数据
     */
    public JSONObject addUser(JSONObject jsonObject){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String jsonStr = JSONUtil.toJsonStr(jsonObject);
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/company/people/simpleAdd") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                    .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                    .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject object = new JSONObject(responseBody.string());
                return object;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }

    /**
     * 修改用户数据
     */
    public JSONObject updateUser(JSONObject jsonObject){
        // 先获取token
        if (userToken == null) {
            setToken();
        }

        try {
            String jsonStr = JSONUtil.toJsonStr(jsonObject);
            // 创建请求
            Request request = new Request.Builder()
                    .url(url + "/company/people/simpleAdd") // 使用配置URL
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json"), jsonStr))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + userToken.toString()) // 添加认证头
                    .build();

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS) // 连接超时
                    .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)    // 读取超时
                    .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)   // 写入超时
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                JSONObject object = new JSONObject(responseBody.string());
                return object;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 流式处理响应
        return null;
    }


    /**
     * 上传word文件，获取文件中的内容
     */
    @PostMapping("/importFile")
    public Map<String, Object> importFile(@RequestParam("file") MultipartFile file) throws Exception {
        Map<String, Object> response = new HashMap<>();
        boolean isDoc =  file.getOriginalFilename().endsWith(".doc");
        String html = WordToHtmlUtil.convertWordToHtml(file.getInputStream(), isDoc);
//        String html = WordUtils.convertWordToHtmlString(file);
        response.put("html", html);
        return response;
    }

    /**
     * 将html内容导出为docx文档
     */
    @PostMapping("/exportFile")
    public byte[] exportFile(@RequestBody Map<String, String> obj) throws Exception {
        try {
            String html = obj.get("htmlBody");
            // 创建内存输出流
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            // 使用 Aspose.Words 将 HTML 插入 Word 并写入输出流
            WordUtils.HtmlToWord(html, outputStream);
            // 返回响应
            byte[] byteArray = outputStream.toByteArray();
            return byteArray;

        } catch (Exception e) {
            throw new IOException("导出Word失败: " + e.getMessage());
        }
    }

}
